param(
	[string]$resetIndex = $true
)

function StartCrawl(){
	$searchScopes = Get-SPEnterpriseSearchServiceApplication | Get-SPEnterpriseSearchCrawlContentSource
	
	
	foreach($searchScope in $searchScopes){
		$name = $searchScope.Name
		
		if($searchScope.CrawlState -eq 'Idle'){
		
			Write-Host -ForegroundColor Yellow "Starting full crawl for $name"
			$searchScope.StartFullCrawl();
				sleep 5
			
			if($searchScope.CrawlState -eq 'Idle'){
				Write-Host -NoNewLine -ForegroundColor Yellow "waiting to crawl $name"
				while($searchScope.CrawlState -eq 'Idle'){
					Write-Host -NoNewLine . -ForegroundColor Magenta
		            Start-Sleep -Seconds 2
				}
			}
			
			Write-Host 
			if($searchScope.CrawlState -eq 'CrawlStarting'){
				Write-Host -NoNewLine -ForegroundColor Magenta "starting to crawl $name"
				While($searchScope.CrawlState -eq 'CrawlStarting'){
					Write-Host -NoNewLine . -ForegroundColor Magenta
		            Start-Sleep -Seconds 2
				}
			}
			
			Write-Host 
			if($searchScope.CrawlState -eq 'CrawlingFull'){
				Write-Host -NoNewLine -ForegroundColor Magenta "crawling $name"
				While($searchScope.CrawlState -eq 'CrawlingFull'){
					Write-Host -NoNewLine . -ForegroundColor Magenta
		            Start-Sleep -Seconds 5
				}
			}
			
			Write-Host 
			if($searchScope.CrawlState -eq 'CrawlCompleting'){
				Write-Host -NoNewLine -ForegroundColor Magenta "stopping to crawl  $name"
				While($searchScope.CrawlState -eq 'CrawlCompleting'){
					Write-Host -NoNewLine . -ForegroundColor Magenta
		            Start-Sleep -Seconds 2
				}
			}
			
			Write-Host -ForegroundColor Green "crawl is complete for $name"
			Write-Host
			
		}
	}
}


if((Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue ) -eq $null){
	Add-PSSnapin Microsoft.SharePoint.PowerShell
}

if($resetIndex){
	$searchApp = Get-SPEnterpriseSearchServiceApplication                                                    

	if($searchApp -ne $null) {
		Write-Host "Resetting Content Index ..." -ForegroundColor Yellow
	  $searchAppCtx = [Microsoft.Office.Server.Search.Administration.SearchContext]::GetContext($searchApp)

	  $searchAppCtx.Reset($true)
	}
}


StartCrawl